﻿using System;
using System.Collections.Generic;
using System.Data;
using PSE.Deployment.ConfigurationManager.Controls;
using PSE.Deployment.SetupBase.Parameter;
using PSE.Deployment.SetupBase.Parameter.Enums;
using Sinacor.Deployment.Setup.DataAccess;
using Sinacor.Deployment.Setup.Parameter;

namespace Sinacor.Deployment.ConfigurationManager.UI
{
	public partial class MainWindow : PSE.Deployment.ConfigurationManager.UI.WindowBase
	{
		public MainWindow()
		{
			this.WindowTitle = "Sinacor Configuration Manager";
		}

		DataBaseConnection _databaseConnection = null;
		PrerequisitesStatus _databasePreRequisites = PrerequisitesStatus.NotOk;

		protected override bool IsDataBaseInstalledCorrectly
		{
			get
			{
				return ((_databaseConnection != null) && _databasePreRequisites == PrerequisitesStatus.Ok);
			}
		}

		protected override Type GetParameterType()
		{
			return typeof(SinacorParameter);
		}

		protected override void LoadParameterDatabaseInfo(SetupParameter param)
		{
			SinacorParameter sinacorParameter = param as SinacorParameter;

			if (sinacorParameter != null && sinacorParameter.DataBase != null && sinacorParameter.DataBase.ConnectionInfo != null && !(String.IsNullOrEmpty(sinacorParameter.DataBase.ConnectionInfo.TNSName)))
			{
				_databaseConnection = sinacorParameter.DataBase.ConnectionInfo;
				_databasePreRequisites = sinacorParameter.Prerequisites.DataBase;
			}
		}

		protected override List<SimpleComboItem> RetrieveQuery(string sqlCommand)
		{
			List<SimpleComboItem> result = new List<SimpleComboItem>();

			using (OracleDataBase db = new OracleDataBase(_databaseConnection.User, PSE.Deployment.Util.EncryptDecrypt.Decrypt(_databaseConnection.Password), _databaseConnection.TNSName, _databaseConnection.IsEncrypted))
			{
				using (IDataReader dr = db.ExecuteReader(sqlCommand))
				{
					if (dr.Read())
					{
						do
						{
							if (dr.FieldCount >= 2)
								result.Add(new SimpleComboItem(dr[0].ToString(), dr[1].ToString()));
							else
								result.Add(new SimpleComboItem(dr[0].ToString(), dr[0].ToString()));

						} while (dr.Read());

						dr.Close();
					}
				}
			}

			return result;
		}

		protected override string SystemId
		{
			get { return "Sinacor-v1"; }
		}
	}
}